package com.empire.module.member.service.relationship;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.empire.module.member.controller.admin.relationship.vo.GraphDataVO;
import com.empire.module.member.controller.admin.relationship.vo.LinkVO;
import com.empire.module.member.controller.admin.relationship.vo.NodeVO;
import com.empire.module.member.dal.dataobject.relation.NodeDo;
import com.empire.module.member.dal.dataobject.relation.RelationshipDo;
import com.empire.module.member.dal.mysql.relationship.NodeMapper;
import com.empire.module.member.dal.mysql.relationship.RelationshipMapper;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class GraphServiceImpl implements GraphService {

    @Resource
    private NodeMapper nodeMapper;

    @Resource
    private RelationshipMapper relationshipMapper;

    @Override
    public GraphDataVO getGraphData(Integer id) {
        // 查询所有节点
        LambdaQueryWrapper<NodeDo> query = new LambdaQueryWrapper<>();
        query.eq(NodeDo::getPersonId, id);
        List<NodeDo> nodes = nodeMapper.selectList(query);
        // 查询所有关系
        LambdaQueryWrapper<RelationshipDo> rew = new LambdaQueryWrapper<>();
        rew.eq(RelationshipDo::getPersonId, id);
        List<RelationshipDo> relationships = relationshipMapper.selectList(rew);

        GraphDataVO result = new GraphDataVO();

        // 转换节点
        result.setNodes(nodes.stream().map(node -> {
            NodeVO vo = new NodeVO();
            vo.setId(node.getId().toString());
            vo.setName(node.getName());
            vo.setGroup(node.getGroup());
            vo.setSize(node.getSize());
            return vo;
        }).collect(Collectors.toList()));

        // 转换关系
        result.setLinks(relationships.stream().map(relationship -> {
            LinkVO vo = new LinkVO();
            vo.setSource(relationship.getSourceId().toString());
            vo.setTarget(relationship.getTargetId().toString());
            vo.setValue(relationship.getValue());
            return vo;
        }).collect(Collectors.toList()));

        return result;
    }
}
